<?php

namespace Modules\Manager\Http\Controllers;

use App\Helpers\ResponseData;
use App\Models\User;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Modules\Manager\Entities\Department;
use Modules\Manager\Helpers\UserData;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{
    use ResponseData,UserData;
    public function list(User $user,Request $request){
        $size = $request->input('size',10);
        $data = $user->query()->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }

    public function get(Request $request){
        $post = Role::query()->get();
        $department = Department::query()->get();
        return $this->success(compact('post','department'));
    }
    public function edit(User $user,Request $request){
        $data = $user->find($request->id);
        return $this->success($data);
    }
    public function update(User $user,Request $request){
        $data = $user->find($request->id);
        $array = $request->only('role','department','username','password');
        if($request->filled('password')){
            $array['password'] = Hash::make($request->password);
        }
        $data->update($array);
        return $this->success('修改成功');
    }

    public function login(Request $request){
        $account = User::query()->where('username',$request->username)->first();
        if($account){
            if (Hash::check($request->password, $account->password)) {
                $data = $this->respondWithToken($account,$request);
                return $this->success($data);
            }else{
                return $this->failed('请输入正确的账号密码',201);
            }
        }else{
            return $this->failed('请输入正确的账号密码',201);
        }

    }

    //重设密码
    public function resetPwd(Request $request){
        $account = $request->user();
        if (Hash::check($request->password, $account->password)) {
            $account->password = Hash::make($request->new_password);
            $account->save();
            return $this->success('修改密码成功');
        }else{
            return $this->failed('请输入正确的账号密码',201);
        }
    }
}
